package com.sup.generator.http;

import com.sup.generator.entity.GrUserEntity;
import com.sup.generator.exception.GrException;
import com.sup.generator.fixedvalue.GrConst;
import com.sup.generator.fixedvalue.GrMessage;
import com.sup.generator.service.GrRedisService;
import com.sup.generator.utils.GrBase64Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author Zh
 * @version v1.0
 * @description: 用户参数解析器
 * @date 2020/11/13 20:13
 */
@Service
public class GrUserArgumentResolvers implements HandlerMethodArgumentResolver {

    @Autowired
    GrRedisService redisService;

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        if(methodParameter.getParameterType().equals(GrUserEntity.class)){
            return true;
        }
        return false;
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        HttpServletRequest request = (HttpServletRequest) nativeWebRequest.getNativeRequest();
        HttpServletResponse response = (HttpServletResponse) nativeWebRequest.getNativeResponse();
        String auth = request.getHeader(GrConst.AUTHORIZATION);
        if("".equals(auth)){
            response.setCharacterEncoding("UTF-8");
            throw new GrException(GrMessage.NOT_LOGIN);
        }
        String redisKey = GrBase64Util.base64Decryption(auth);
        GrUserEntity userEntity = redisService.get(redisKey,GrUserEntity.class);
        return userEntity;
    }
}
